const fs = require('fs-extra')
const path = require('path')
const { v4: uuid } = require('uuid')
const { getVideoDuration } = require('./utils/util')
const { transformToHls } = require('./utils/ffmpeg')

// a. 读取指定目录下的所有文件
const arr = fs.readdirSync(path.join(__dirname, './video'))
// b. 处理文件
const promises = arr.map(async (item, index) => {
  // 1. 根据序号计算出id
  const id = uuid()
  const obj = { id: id, name: item, duration: 0 }
  // 2. 获取视频时长
  const videoDir = path.join(__dirname, `./video/${item}`)
  const duration = await getVideoDuration(videoDir)
  obj.duration = duration
  // 3. 避免出现不存在问题
  const outputDir = path.join(__dirname, `./output/${id}/index.m3u8`)
  fs.createFileSync(outputDir)
  // 4. 切片转码
  await transformToHls(videoDir, outputDir)
  return obj
})
// 3. 将结果生成到category.json文件中
Promise.all(promises).then(res => {
  const list = fs.readFileSync(path.join(__dirname, './category.json'))
  fs.writeFileSync(path.join(__dirname, './category.json'), JSON.stringify([...list, ...res], null, 2))
}).catch(error => {
  console.log('error', error)   
})